import { ComponentClass } from 'react'
import { connect } from '@tarojs/redux'
import Taro, {Component, Config} from '@tarojs/taro'
import { View, Swiper, SwiperItem, Image, ScrollView } from '@tarojs/components'
import { SDBody } from 'sudao-ui'
import SDUtils from 'sudao-utils'

import PageProps from '../../../redux'
import { login, logout } from '../../../redux/actions'

import GoodsItem from '../../../comps/goods-item'

import SilverPriceIcon from '../../../images/ic_money.png'
import HomeAdultIcon from '../../../images/ic_home_adult.png'
import HomeCouplesIcon from '../../../images/ic_home_couples.png'
import HomeFashionIcon from '../../../images/ic_home_fashion.png'
import HomeKidIcon from '../../../images/ic_home_kid.png'
import HomeOldIcon from '../../../images/ic_home_old.png'
import HomeMoreIcon from '../../../images/ic_next.png'

import './index.less'

type PageState = {
  mainIsLoading: boolean,
  bannerIndex: number,
  bannerList: any[],
  silverPriceData: any,         // 今日银价
  newsDataList: any[],
  recommendDataList: any[],
  subjectDataList: any[]
}

type PageOwnProps = {}

interface TabBarHomePage {
  props: PageProps & PageOwnProps
}

@connect(({userState}) => ({
  userState
}), (dispatch) => ({
  login(userInfo) {
    dispatch(login(userInfo))
  },
  logout() {
    dispatch(logout())
  }
}))
class TabBarHomePage extends Component<PageOwnProps, PageState> {

  config: Config = {
    enablePullDownRefresh: true
  }

  constructor(args) {
    super(args)

    this.state = {
      mainIsLoading: true,
      bannerIndex: 0,
      bannerList: [],
      silverPriceData: {},
      newsDataList: [],
      recommendDataList: [],
      subjectDataList: []
    }
  }

  componentDidMount () {
    this.fetchData()
  }

  onPullDownRefresh () {
    this.fetchData()
  }

  fetchData = async () => {
    let silverPriceData:any = {}        // 今日银价
    let bannerList: any[] = []          // 轮播图
    let newsDataList: any[] = []        // 新品上架
    let recommendDataList: any[] = []   // 新品推荐
    let subjectDataList: any[] = []     // 专题推荐


    try {
      silverPriceData = await SDUtils.doGet('/wxmini/silverPrice/newest')
      bannerList = await SDUtils.doGet('/ext/wxmini/swiperItem/MINI_BANNER/code')
      let newsDataResp = await SDUtils.doGet('/wxmini/traderProduct', {
        offset: 6,
        limit: 6,
        traderId: '1'
      })
      newsDataList = newsDataResp.items || []
      let recommendDataResp = await SDUtils.doGet('/wxmini/traderProduct', {
        offset: 10,
        limit: 4,
        traderId: '1'
      })
      recommendDataList = recommendDataResp.items || []
      subjectDataList = ['/-99/20181225/161906/026/', '/-99/20181225/161928/525/']
    } catch (e) {
      SDUtils.showMsg(e)
    } finally {
      Taro.stopPullDownRefresh()
      this.setState({
        mainIsLoading: false,
        silverPriceData: silverPriceData,
        newsDataList: newsDataList,
        recommendDataList: recommendDataList,
        subjectDataList: subjectDataList,
        bannerList: bannerList
      })
    }
  }

  render () {
    const { bannerList, bannerIndex, mainIsLoading, silverPriceData, newsDataList, subjectDataList, recommendDataList } = this.state
    return (
      <SDBody sd-class='container' showPadding={false} loading={mainIsLoading}>
        <View className='main-banner'>
          <Swiper className='banner-swiper' indicatorDots={false} circular autoplay duration={300} onChange={this.onSwiperChange}>
            {
              bannerList.map((item, index) => {
                return <SwiperItem className='banner-swiper-item' key={index}>
                  <Image src={SDUtils.processImageURL(item.image || '', 750, 440)} mode='aspectFill' lazyLoad className='banner-img' />

                </SwiperItem>
              })
            }
          </Swiper>
          <View className='banner-dots'>
            {
              bannerList.map((_, index) => {
                return <View key={index} className={index == bannerIndex ? `dot-item dot-item_current` : `dot-item`}></View>
              })
            }
          </View>
        </View>

        {/** 今日银价 */}
        <View className='banner-tips'>
          <Image src={SilverPriceIcon} className='icon' />
          <View className='title'>今日银价:{SDUtils.formatPrice(`${silverPriceData.price}`, false)}/g</View>
        </View>

        {/** 九宫格 */}
        <View className='section top-section'>
          <View className='content'>
            <View className='left' onClick={this.gotoProductList}>
              <Image src={HomeFashionIcon} className='content-icon'/>
              <View className='content-title'>时尚</View>
            </View>
            <View className='right'>
              <View className='item' onClick={this.gotoProductList}>
                <Image src={HomeOldIcon} className='content-icon'/>
                <View className='content-title'>老年</View>
              </View>
              <View className='item' onClick={this.gotoProductList}>
                <Image src={HomeAdultIcon} className='content-icon'/>
                <View className='content-title'>成年</View>
              </View>
              <View className='item' onClick={this.gotoProductList}>
                <Image src={HomeKidIcon} className='content-icon'/>
                <View className='content-title'>儿童</View>
              </View>
              <View className='item' onClick={this.gotoProductList}>
                <Image src={HomeCouplesIcon} className='content-icon'/>
                <View className='content-title'>情侣</View>
              </View>
            </View>
          </View>
        </View>

        {/** 新品上架 */}
        <View className='section news-section'>
          <View className='normal-section_header'>
            <View className='title'>新品上架</View>
            <View className='right' onClick={this.gotoMoreNewsGoods}>
              <Image src={HomeMoreIcon} className='more-icon' />
            </View>
          </View>
          <ScrollView className='content' scrollX>
            {
              newsDataList.map((item, index) => {
                return <View className='cell-item' key={index}>
                  <GoodsItem
                    key={index}
                    width={290}
                    height={418}
                    title={item.name}
                    imgUrl={item.coverImage || ''}
                    price={SDUtils.formatPrice(item.minPrice || 0)}
                    extData={{index: index, type: 'newsDataList'}}
                    onClick={this.onGoodsItemTaped}
                  />
                </View>
              })
            }
          </ScrollView>
        </View>

        {/** 专题推荐 */}
        <View className='section special-section'>
          <View className='normal-section_header'>
            <View className='title'>专题推荐</View>
            <View className='right' onClick={this.gotoMoreSpecialPage}>
              <Image src={HomeMoreIcon} className='more-icon' />
            </View>
          </View>
          <View className='special-content'>
            {
              subjectDataList.map((item, index) => {
                return <Image key={index} src={SDUtils.processImageURL(item || '', 750, 360)} lazyLoad mode='aspectFill' className='special-item' onClick={this.gotoProductList} />
              })
            }
          </View>
        </View>

        {/** 产品推荐 */}
        <View className='section goods-section'>
          <View className='normal-section_header'>
            <View className='title'>产品推荐</View>
            <View className='right' onClick={this.gotoMoreRecommendGoods}>
              <Image src={HomeMoreIcon} className='more-icon' />
            </View>
          </View>
          <View className='goods-list'>
            {
              recommendDataList.map((item, index) => {
                return <View key={index} className='goods-item'>
                  <GoodsItem
                    key={index}
                    width={336}
                    height={466}
                    title={item.name}
                    imgUrl={item.coverImage || ''}
                    price={SDUtils.formatPrice(item.minPrice || 0)}
                    extData={{index: index, type: 'recommendDataList'}}
                    onClick={this.onGoodsItemTaped}
                  />
                </View>
              })
            }
          </View>
        </View>

      </SDBody>
    )
  }

  onSwiperChange = e => {
    let index = e.detail.current
    this.setState({
      bannerIndex: index
    })
  }

  gotoMoreNewsGoods = () => {
    SDUtils.jumpTo('/pages/goods/list/index', {
      comeFrom: 'news'
    })
  }

  gotoMoreSpecialPage = () => {
    console.log('进入更多专题')
    SDUtils.jumpTo('/pages/goods/list/index', {
    })
  }

  gotoMoreRecommendGoods = () => {
    SDUtils.jumpTo('/pages/goods/list/index', {
      comeFrom: 'recommend'
    })
  }

  onGoodsItemTaped = (extData: any) => { // 进入商品详情界面
    let index = extData.index
    let type = extData.type
    let productItem: any = {}
    if (type == 'newsDataList') {
      productItem = this.state.newsDataList[index]
    } else if (type == 'recommendDataList') {
      productItem = this.state.recommendDataList[index]
    }
    if (!productItem || !productItem.productId) {
      return
    }
    SDUtils.jumpTo('/pages/goods/detail/index', {productId: productItem.productId})
  }

  gotoProductList = () => {
    SDUtils.jumpTo('/pages/goods/list/index', {
    })
  }
}

export default TabBarHomePage as ComponentClass<PageOwnProps, PageState>
